define([
	'jquery',
	'ResultObject',
	'jquery.html5storage.min',
	'jquery.xml2json',
	'jquery.blockUI'
	],
	function ($, ResultObject) {
		var debug = true;

		function GlobalInfo(){}

		GlobalInfo.prototype.Set = function (key, value){
			$.sessionStorage.setItem(key, JSON.stringify(value));
		}

		GlobalInfo.prototype.Get = function(key){
			return JSON.parse($.sessionStorage.getItem(key));
		}

		GlobalInfo.prototype.CallWebService = function(service, method, params, successCallback, errorCallback){
			var soapParams = '';

			for(var prop in params){
				soapParams += '<' + prop + '>' + params[prop] + '</' + prop + '>';
			}

			var soapEnvelope = '<?xml version="1.0" encoding="utf-8"?> \
						<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
						  	<soap:Body> \
						    	<'+method+' xmlns="http://SISCON.mx/"> \
						      	 ' + soapParams	+
						    	'</'+method+'> \
						 	</soap:Body> \
						</soap:Envelope>';

			$.ajax({
				type: "POST",
				url: debug ? "/services/"+service+".asmx" : "/SISCON/services/"+service+".asmx",
				dataType: "xml",
				data: soapEnvelope,
				headers:{
					'Content-Type': 'text/xml; charset=UTF-8',
					'SOAPAction': '"http://SISCON.mx/' + method + '"'
				},
				success: function(data, statusCode, jqXHRObj){
							var resultObj = new ResultObject(data, method);
							successCallback(resultObj);
						},
				error: function(error){
							errorCallback(error);
						},
				complete: function(){
					
				}
			});
		}

		GlobalInfo.prototype.ShowMessage = function(message, isError, timeout){
			if(isError){
				//alert('jaja lol un error: ' + message);
			}
			//Do some crazy stuff
		}

		GlobalInfo.prototype.DialogShowMessage = function(message, isError, timeout){
			if(isError){
				$('#message').addClass('alert-error');
				$('#message').html(message);	
				$('#message').css('visibility', 'visible');
			}
			if(timeout > 0){
				setTimeout(
					function(){
						$('#message').css('visibility', 'hidden');
					}, timeout
				);
			}
		}

		GlobalInfo.prototype.Logout = function(){
		    var params = {
		      sessionUUID: GlobalInfo.prototype.sessionUUID
		    };
		    GlobalInfo.prototype.CallWebService('SecurityServices', 'Logout', params, GlobalInfo.prototype.LogoutSuccessCallback, GlobalInfo.prototype.LogoutErrorCallback);
		}

		GlobalInfo.prototype.Redirect = function(resource){
			window.location.href = debug ? "/web/html/" + resource : "/SISCON/web/html/" + resource;
		}

		GlobalInfo.prototype.CheckSession = function(){
			if(!GlobalInfo.prototype.sessionUUID || GlobalInfo.prototype.sessionUUID == null){
				GlobalInfo.prototype.Redirect('index.html');
			}
		}

		GlobalInfo.prototype.HasSession = function(){
			if(!GlobalInfo.prototype.sessionUUID || GlobalInfo.prototype.sessionUUID == null){
				return false;
			}
			return true;
		} 

		GlobalInfo.prototype.LogoutErrorCallback = function(error){
		    GlobalInfo.prototype.Redirect('index.html');
			GlobalInfo.prototype.ShowMessage('Ocurri� un error inesperado. Por favor intente m�s tarde.', true, 5000);
		}

		GlobalInfo.prototype.LogoutSuccessCallback = function(result){
		        if(result.error() != null){
				  //ShowMessage('Ocurri� un error inesperado. Por favor intente m�s tarde.', true, 5000);
		        }
		        else{
					GlobalInfo.prototype.DestroySession();
		          	GlobalInfo.prototype.Redirect('index.html');
		        }
		}

		GlobalInfo.prototype.DestroySession = function(){
			$.sessionStorage.clear();
		}

		GlobalInfo.prototype.RequireRole = function(role, accessLevel) {
			var indexFound = -1;

			if(GlobalInfo.prototype.permissions != null){
				for (var i = 0; i < GlobalInfo.prototype.permissions.length; i++) {
					if (GlobalInfo.prototype.permissions[i].Resource == role) {
						indexFound = i;
						break;
					}
				}
			}
			else{
				return false;
			}

			if (indexFound == -1 || GlobalInfo.prototype.permissions[indexFound].AccessLevel == GlobalInfo.prototype.Role.NO_ACCESS) {
				return false;
			} 
			
			if (accessLevel == GlobalInfo.prototype.Role.WRITE_ACCESS && GlobalInfo.prototype.permissions[indexFound].AccessLevel == GlobalInfo.prototype.Role.WRITE_ACCESS) {
				return true;
			} else if (accessLevel == GlobalInfo.prototype.Role.READ_ACCESS && 
				(GlobalInfo.prototype.permissions[indexFound].AccessLevel == GlobalInfo.prototype.Role.WRITE_ACCESS || GlobalInfo.prototype.permissions[indexFound].AccessLevel == GlobalInfo.prototype.Role.READ_ACCESS) ) {
				
				return true;
			}
			
			return false;
		}

		GlobalInfo.prototype.BlockUI = function(message){
			$.blockUI({ 
				css: { 
		            border: 'none', 
		            padding: '15px', 
		            backgroundColor: '#000', 
		            '-webkit-border-radius': '10px', 
		            '-moz-border-radius': '10px', 
		            opacity: .5, 
		            color: '#fff'
		        },
		        message: '<h1><img src="../img/loader.gif" />'+message+'</h1>'
		    });
		}

		GlobalInfo.prototype.UnblockUI = function(){
			$.unblockUI();
		}

		GlobalInfo.prototype.sessionUUID = GlobalInfo.prototype.Get('sessionUUID');
		GlobalInfo.prototype.permissions = GlobalInfo.prototype.Get('permissions');
		GlobalInfo.prototype.displayName = GlobalInfo.prototype.Get('displayName');
		GlobalInfo.prototype.roleId 	 = GlobalInfo.prototype.Get('roleId');
		GlobalInfo.prototype.userId 	 = GlobalInfo.prototype.Get('userId');

		GlobalInfo.prototype.Role = {
			WRITE_ACCESS: 	'W',
			READ_ACCESS	: 	'R',
			NO_ACCESS	: 	'N',
			USERS: 			'Users',
			ROLES: 			'Roles',
			UPLOADS: 		"Uploads",
			TEACHERS: 		"Teachers",
			COURSES: 		"Courses",
			CLASSROOMS: 	"Classrooms",
			DEPARTMENTS: 	"Departments"
		}

		var global = new GlobalInfo();

		return global;
	}
);